//
//  HSRequest.m
//  Wutuojia
//
//  Created by anlun on 15/7/17.
//  Copyright (c) 2015年 anLun. All rights reserved.
//

#import "HSRequest.h"

#import "NSObject+MJKeyValue.h"
//#import "HSShortOperationMacro.h"

//#import "HSUtilities.h"
#import "NSString+UrlEncode.h"
//#import "SRUtils.h"
//#import "HSUserAction.h"
#import "ALDBManage+Cache.h"
//#import "HSLoadingView.h"
//#import "HSComAction.h"

@interface HSRequest()
@end
@implementation HSRequest
/*
+ (AFHTTPSessionManager *)sharedInstance {
	static dispatch_once_t once;
	static AFHTTPSessionManager *_manager;
	dispatch_once(&once, ^{
		_manager= [AFHTTPSessionManager manager];
	});
	return _manager;
}

+(void)requestApiName:(NSString *)apiName
			andParams:(NSDictionary *)params
			andMethod:(ReqeustMethodEnum)method
		 successBlcok:(void(^)(id sucContent))successBlock
		  failedBlock:(void(^)(id failContent))failedBlock
		 reloginBlock:(void(^)(id reloginContent))reloginBlock{
	
	__block NSString *urlStr = [NSString stringWithFormat:@"%@%@",
				  GetApiByKey(@"host"),
				  GetApiByKey(apiName)
				  ];
	NSMutableDictionary *mulParams=[[NSMutableDictionary alloc] initWithCapacity:2];
	[mulParams addEntriesFromDictionary:params];
    [[HSComAction sharedInstance] checkUrlHasRequest:[NSString stringWithFormat:@"%@?%@",urlStr,[SRUtils buildRequestUrlWithParams:@"" params:mulParams]] isCheck:YES call:^(BOOL hasRequest) {
        if (hasRequest) {
            return;
        }
    }];
	if ([urlStr containsString:@"/auth/"]) { //要用户认证，所以，多传了一些参数
		[mulParams addEntriesFromDictionary:[[HSComAction sharedInstance] getAuthDic]];
	}else{
	}
	NSString *str= [SRUtils buildRequestUrlWithParams:@"" params:mulParams];
	NSData *postData = [str dataUsingEncoding:NSUTF8StringEncoding];
	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
	
	// 设置超时时间
//	[[HSRequest sharedInstance].requestSerializer willChangeValueForKey:@"timeoutInterval"];
//	[HSRequest sharedInstance].requestSerializer.timeoutInterval = 2.f;
//	[[HSRequest sharedInstance].requestSerializer didChangeValueForKey:@"timeoutInterval"];
	
	[urlRequest setTimeoutInterval:kNetTimeoutInterval]; //设置超时时间
	[urlRequest setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
	[urlRequest setValue:@"json" forHTTPHeaderField:@"bfw-ctrl"];
	[urlRequest setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
	[HSRequest sharedInstance].responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

	//添加版本
	NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
	NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
	NSString *app_shortbuild=[infoDictionary objectForKey:@"CFBundleShortVersionString"];
	[urlRequest setValue:filterStr(app_build) forHTTPHeaderField:@"version"];
	[urlRequest setValue:filterStr(app_shortbuild) forHTTPHeaderField:@"shortVesion"];
	
	//添加平台信息
	[urlRequest setValue:@"IOS" forHTTPHeaderField:@"plat"];
	
	switch (method) {
		case Get_type:
		{
			[urlRequest setHTTPMethod:@"GET"];
			break;
		}
		case Post_type:
		{
			[urlRequest setHTTPMethod:@"POST"];
			break;
		}
		default:
			break;
	}
    NSLog(@"url=%@?%@",urlStr,str);
	[urlRequest setHTTPBody:postData];
	showLoadView?[[[HSComAction sharedInstance] curCtrl] show]:@"";
	NSURLSessionDataTask *sessionTask=[[HSRequest sharedInstance] dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [[HSComAction sharedInstance] checkUrlHasRequest:[NSString stringWithFormat:@"%@?%@",urlStr,str] isCheck:NO call:^(BOOL hasRequest) {
        }];
		showLoadView?[[[HSComAction sharedInstance] curCtrl] hide]:@"";
		showLoadView=NO;
		if (!error) {
			if ([responseObject[@"code"] integerValue] ==-2||[responseObject[@"code"] integerValue] ==-4) {
				//第三方登录，暂不做处理，token过时，照样弹出登录界面
				NSString *userName=[[NSUserDefaults standardUserDefaults] objectForKey:@"userLoginNameAndPwd"][@"userName"];
				NSString *password=[[NSUserDefaults standardUserDefaults] objectForKey:@"userLoginNameAndPwd"][@"password"];
				
				if (!(password&&password.length>0)) { //当本地未缓存用户名密码时
					[[HSUserAction sharedInstance] toLoginCallBack:^(id sender) {
						NSMutableDictionary *mulDic=[NSMutableDictionary dictionaryWithDictionary:params];
						[mulDic setObject:[HSUserAction getUserId] forKey:@"userId"];
						[mulDic setObject:[HSUserAction getUniqueCode] forKey:@"uniqueCode"];
						if ([mulDic[@"act"] isEqualToString:@"login"]) {
							return;
						}
						[HSRequest requestApiName:apiName
										andParams:mulDic
										andMethod:method
									 successBlcok:successBlock
									  failedBlock:failedBlock
									 reloginBlock:reloginBlock];
					} andDelegate:nil];
				}else{ //当本地缓存了用户名密码时
					[[HSUserAction sharedInstance] login:userName pwd:password callBack:^(id sender) {
						if (!sender) {
							[[HSUserAction sharedInstance] toLoginCallBack:^(id sender) {
								NSMutableDictionary *mulDic=[NSMutableDictionary dictionaryWithDictionary:params];
								[mulDic setObject:[HSUserAction getUserId] forKey:@"userId"];
								[mulDic setObject:[HSUserAction getUniqueCode] forKey:@"uniqueCode"];
								if ([mulDic[@"act"] isEqualToString:@"login"]) {
									return;
								}
								[HSRequest requestApiName:apiName
												andParams:mulDic
												andMethod:method
											 successBlcok:successBlock
											  failedBlock:failedBlock
											 reloginBlock:reloginBlock];
							} andDelegate:nil];
						}else{
							NSMutableDictionary *mulDic=[NSMutableDictionary dictionaryWithDictionary:params];
							[mulDic setObject:[HSUserAction getUserId] forKey:@"userId"];
							[mulDic setObject:[HSUserAction getUniqueCode] forKey:@"uniqueCode"];
							[HSRequest requestApiName:apiName
											andParams:mulDic
											andMethod:method
										 successBlcok:successBlock
										  failedBlock:failedBlock
										 reloginBlock:reloginBlock];
						}
					}];
				}
				
			}else if ([responseObject[@"code"] integerValue] ==-1){
				if(failedBlock){
					[[HSComAction sharedInstance] showLoadWarn:responseObject[@"msg"]];
					failedBlock(responseObject);
				}
			}else if ([responseObject[@"code"] integerValue] ==-300){
				if (successBlock) {
					successBlock(responseObject);
				}
			}else if([responseObject[@"code"] integerValue] ==1){
				if (successBlock) {
					successBlock(responseObject);
				}
			//存入缓存数据
			NSString *keyStr=[NSString stringWithFormat:@"%@%@%@",response.URL,params[@"act"],[HSUserAction getUniqueCode]];
			[[HSDBManage standarDBManage] addCacheVal:responseObject forKey:keyStr];
			}else if([responseObject[@"code"] integerValue] ==0){
				if (successBlock) {
					successBlock(responseObject);
				}
			}else{
				if(failedBlock){
//					if ([responseObject[@"code"] integerValue]==10001) { //用户名或密码错误
//					}else{
						[[HSComAction sharedInstance] showLoadWarn:responseObject[@"msg"]];
						failedBlock(responseObject);
//					}
				}
			}
		}else{
			if (error.code==-1009) {
				[[HSComAction sharedInstance] showLoadWarn:@"似乎已断开与互联网的连接"];
				//读取缓存数据
				NSString *keyStr=[NSString stringWithFormat:@"%@%@%@",error.userInfo[@"NSErrorFailingURLKey"],params[@"act"],[HSUserAction getUniqueCode]];
				id responseObject= [[HSDBManage standarDBManage] cacheValForKey:keyStr];
				if (responseObject) {
					if (successBlock&&responseObject) {
						successBlock(responseObject);
					}
				}else{
					if(failedBlock){
						failedBlock(response);
					}
				}
			}else if(error.code==-1001){
				[[HSComAction sharedInstance] showLoadWarn:@"请求超时"];
				if(failedBlock){
					failedBlock(response);
				}
			}else{
				if(failedBlock){
					failedBlock(response);
				}
			}
		}
	}];
	[[HSRequest sharedInstance] requestSerializer].cachePolicy=NSURLRequestReloadIgnoringLocalCacheData;
	[sessionTask resume];
	
}
+(void)requestApiName:(NSString *)apiName
			andParams:(NSDictionary *)params
			andMethod:(ReqeustMethodEnum)method
		 successBlcok:(void(^)(id sucContent))successBlock
		  failedBlock:(void(^)(id failContent))failedBlock
		 reloginBlock:(void(^)(id reloginContent))reloginBlock
		  andShowLoad:(BOOL)show andDelegate:(id)sender{
//	HSBaseViewController *curCtrl=(HSBaseViewController *)sender;
//		[[HSRequestStore standarRequestStore] setShowLoadView:show];
//	[[HSLoadingView sharedInstance] setTheCurCtrl:sender];
	[[HSComAction sharedInstance] setCurCtrl:sender];
	showLoadView=show;
	[HSRequest requestApiName:apiName andParams:params andMethod:method successBlcok:successBlock failedBlock:failedBlock reloginBlock:reloginBlock];
}
+(void)requestApiName:(NSString *)apiName
			andIsTest:(BOOL)test
			andParams:(NSDictionary *)params
			andMethod:(ReqeustMethodEnum)method
		 successBlcok:(void(^)(id sucContent))successBlock
		  failedBlock:(void(^)(id failContent))failedBlock
		 reloginBlock:(void(^)(id reloginContent))reloginBlock{
	NSString *urlStr=nil;
		NSString *str=GetApiByKey(apiName);
		NSString *str2=[[str componentsSeparatedByString:@"/"] lastObject];
		NSString *str3=[[str2 componentsSeparatedByString:@"."] firstObject];
		NSString *str4=str3;
	NSString *str5=[NSString stringWithFormat:@"%@%@",str4,params[@"act"]];
		str4=[NSString stringWithFormat:@"%@.json",str5];
		
		urlStr=[NSString stringWithFormat:@"file:///%@",[HSUtilities bundlePath:str4]];
	
	NSString *strstr= [SRUtils buildRequestUrlWithParams:@"" params:params];
	NSData *postData = [strstr dataUsingEncoding:NSUTF8StringEncoding];
	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
	
	// 设置超时时间
	//	[[HSRequest sharedInstance].requestSerializer willChangeValueForKey:@"timeoutInterval"];
	//	[HSRequest sharedInstance].requestSerializer.timeoutInterval = 2.f;
	//	[[HSRequest sharedInstance].requestSerializer didChangeValueForKey:@"timeoutInterval"];
	
	[urlRequest setTimeoutInterval:kNetTimeoutInterval]; //设置超时时间
	[urlRequest setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
	[urlRequest setValue:@"json" forHTTPHeaderField:@"bfw-ctrl"];
	[urlRequest setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
	[HSRequest sharedInstance].responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
	
	//添加版本
	NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
	NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
	NSString *app_shortbuild=[infoDictionary objectForKey:@"CFBundleShortVersionString"];
	[urlRequest setValue:filterStr(app_build) forHTTPHeaderField:@"version"];
	[urlRequest setValue:filterStr(app_shortbuild) forHTTPHeaderField:@"shortVesion"];
	
	//添加平台信息
	[urlRequest setValue:@"IOS" forHTTPHeaderField:@"plat"];
	
	switch (method) {
		case Get_type:
		{
			[urlRequest setHTTPMethod:@"GET"];
			break;
		}
		case Post_type:
		{
			[urlRequest setHTTPMethod:@"POST"];
			break;
		}
		default:
			break;
	}
	NSLog(@"url=%@?%@",urlStr,str);
	[urlRequest setHTTPBody:postData];
	showLoadView?[[[HSComAction sharedInstance] curCtrl] show]:@"";
	NSURLSessionDataTask *sessionTask=[[HSRequest sharedInstance] dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
		showLoadView?[[[HSComAction sharedInstance] curCtrl] hide]:@"";
		showLoadView=NO;
		if (!error) {
			if ([responseObject[@"code"] integerValue] ==-2||[responseObject[@"code"] integerValue] ==-4) {
				[[HSUserAction sharedInstance] toLoginCallBack:^(id sender) {
					NSMutableDictionary *mulDic=[NSMutableDictionary dictionaryWithDictionary:params];
					[mulDic setObject:[HSUserAction getUserId] forKey:@"userId"];
					[mulDic setObject:[HSUserAction getUniqueCode] forKey:@"uniqueCode"];
					[HSRequest requestApiName:apiName andParams:mulDic andMethod:method successBlcok:successBlock failedBlock:failedBlock reloginBlock:reloginBlock];
				} andDelegate:nil];
			}else if ([responseObject[@"code"] integerValue] ==-1){
				if(failedBlock){
					failedBlock(responseObject);
				}
			}else if([responseObject[@"code"] integerValue] ==1){
				if (successBlock) {
					successBlock(responseObject);
				}
				//存入缓存数据
				NSString *keyStr=[NSString stringWithFormat:@"%@%@%@",response.URL,params[@"act"],[HSUserAction getUniqueCode]];
				[[HSDBManage standarDBManage] addCacheVal:responseObject forKey:keyStr];
			}else{
				[[HSComAction sharedInstance] showLoadWarn:responseObject[@"msg"]];
			}
		}else{
			if (error.code==-1009) {
				[[HSComAction sharedInstance] showLoadWarn:@"似乎已断开与互联网的连接"];
				//读取缓存数据
				NSString *keyStr=[NSString stringWithFormat:@"%@%@%@",error.userInfo[@"NSErrorFailingURLKey"],params[@"act"],[HSUserAction getUniqueCode]];
				id responseObject= [[HSDBManage standarDBManage] cacheValForKey:keyStr];
				if (responseObject) {
					if (successBlock&&responseObject) {
						successBlock(responseObject);
					}
				}else{
					if(failedBlock){
						failedBlock(response);
					}
				}
			}else if(error.code==-1001){
				[[HSComAction sharedInstance] showLoadWarn:@"请求超时"];
			}else{
				if(failedBlock){
					failedBlock(response);
				}
			}
		}
	}];
	[[HSRequest sharedInstance] requestSerializer].cachePolicy=NSURLRequestReloadIgnoringLocalCacheData;
	[sessionTask resume];
	

}
 */
@end
